package com.pig4cloud.pigx.common.security.service;

import com.pig4cloud.pigx.admin.api.entity.ToCUser;
import com.pig4cloud.pigx.admin.api.feign.RippleRemoteUserService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

@RequiredArgsConstructor
public class RippleTocUserDetailsServiceImpl implements PigxUserDetailsService {

    private final RippleRemoteUserService remoteUserService;

    // 登录流程获取token使用
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        ToCUser user = remoteUserService.userInfo(username, SecurityConstants.FROM_IN).getData();
        Boolean enabled = true;
        //判断用户是否禁用
        if (user.getStatus().equals(1)) {
            enabled = false;
        }
        //用户名和密码为数据库中存储的授权钱包地址
        return new PigxUser(Long.valueOf(user.getUid()), user.getAddress(), null,
                "Phone", "Avatar", user.getUid(),
                user.getUid(), user.getEmail(), 1L,
                "{noop}" + user.getAddress(), enabled, true,
                true, true, AuthorityUtils.NO_AUTHORITIES,
                user.getLanguageCode());
    }

    // check-token 校验token使用
    @Override
    public UserDetails loadUserByUser(PigxUser pigxUser) {
        // 根据 pigxUser 里面的信息 查询对应表 返回 UserDetails，pigxUser.getUsername()为数据库存储的 授权钱包地址
        return this.loadUserByUsername(pigxUser.getUsername());
    }


    @Override
    public boolean support(String clientId, String grantType) {
        return "dapp".equals(clientId);
    }

    /**
     * 排序值
     *
     * @return 排序值
     */
    @Override
    public int getOrder() {
        return 10;
    }

}


